package com.cjt.security;

import cn.hutool.core.util.StrUtil;
import com.cjt.common.exception.JwtException;
import com.cjt.pojo.User;
import com.cjt.service.UserService;
import com.cjt.utils.JwtUtils;
import com.cjt.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.jar.JarException;


//Jwt拦截器  任何登陆后的数据处理接口都会被此拦截器拦截
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    UserDetailServiceImpl userDetailsService;
    @Autowired
    UserService userService;



    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtils.getHeader());


        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }
        Claims claims = jwtUtils.getClaimsByToken(jwt);
        if (claims == null) {
            JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint = new JwtAuthenticationEntryPoint();
            jwtAuthenticationEntryPoint.commence(request,response,new JwtException("请先登录"));
            throw  new JwtException("请先登录");
        }
        if (jwtUtils.isTokenExpired(claims)) {
            throw new JwtException("token 过期");
        }
        //从jwt获取到是用户名
        String username = claims.getSubject();
        //获取用户授权的权限信息
        User byUsername = userService.getByUsername(username);
        //TODO 通过用户名查看jwt是否在Redis中存在
//        String redis = (String) redisUtil.get(String.valueOf(byUsername.getUsername()));
//        if (!jwt.equals(redis)) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            throw new JwtException("出现致命错误，请联系工作人员");
//        }

        //通过userid查询该用户的角色编码 以及 菜单操作编码
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, null, userDetailsService.getUserAuthority(byUsername.getId()));
        //获取权限信息封装到Authentication中
        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request, response);
    }
}
